package offer;

import java.util.Arrays;

/**
 * @Author Elephas
 * @Date 2022/1/18
 **/
public class ThreeSumClosest {

    /**
     * 数组中三数之和，和最接近于 target
     * @param nums
     * @param target
     * @return
     */

    /*
        思路： 排序 + 双指针
     */
    public int threeSumClosest(int[] nums,int target){
        Arrays.sort(nums);
        int left,right;
        int minSum = nums[2]+nums[1]+nums[0];
        int minAbs = Math.abs(target-minSum);
        for (int i = 0; i < nums.length; i++) {
            left = i+1;
            right = nums.length-1;
            while(left < right){
                int sum = nums[left] + nums[right] + nums[i];
                if(Math.abs(sum - target) < minAbs){
                minSum = sum;
                minAbs = Math.abs(sum - target);
                }
                if( sum == target){
                    return target;
                }else if(sum < target){
                    left++;
                }else{
                    right--;
                }
            }
        }
        return minSum;
    }
    
}
